package com.zjw.concurrency.interview;

import java.util.concurrent.atomic.AtomicInteger;

public class TicketSystemNoLock {
    private final AtomicInteger tickets = new AtomicInteger(100); // 原子操作

    public static void main(String[] args) {
        TicketSystemNoLock ticketSystem = new TicketSystemNoLock();
        for (int i = 1; i <= 10; i++) {
            new Thread(() -> ticketSystem.sellTicketNoLock(), "用户" + i).start();
        }
    }

    private void sellTicketNoLock() {
        while (true) {
            int current = tickets.get();
            if (current <= 0) break;
            if (tickets.compareAndSet(current, current - 1)) { // CAS操作
                System.out.println(Thread.currentThread().getName() + " 抢到第 " + current + " 张票");
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
